package o2o.service.company.postman;

import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.company.postman.PostCompanySalaryCalcInfo;

import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Jahnke【1029777564@qq.com】
 * @ClassName PostManAndCompanySalryCalcService
 * @Description:
 * @date 2019/8/22 12:05
 * @Version 1.0
 */
public class PostManAndCompanySalryCalcService {
    private PostManAndCompanySalryCalcService() {
    }

    enum Singleton {
        INSTANCE;
        private PostManAndCompanySalryCalcService single;

        private Singleton() {
            single = new PostManAndCompanySalryCalcService();
        }

        private PostManAndCompanySalryCalcService getInstance() {
            return single;
        }
    }

    public static PostManAndCompanySalryCalcService getInstance() {
        return Singleton.INSTANCE.single;
    }

    private static Map<String, PostCompanySalaryCalcInfo> dataMap = new ConcurrentHashMap<>();

    // 获取配送员和配送公司的订单累加信息
    public PostCompanySalaryCalcInfo get(String username, Long companyId) throws SQLException {
        String key = null;
        if (dataMap.containsKey(key = getKey(username, companyId))) {
            return dataMap.get(key);
        }
        // 查询数据库
        String sql = "select * from " + PojoTables.POST_COMPANY_CALC_SALARY + " where username='" + username + "' and companyId=" + companyId;

        PostCompanySalaryCalcInfo info = null;
        info = (PostCompanySalaryCalcInfo) UserDaoSql.getInstance().getObject(PostCompanySalaryCalcInfo.class, sql);

        if (info == null) {
            info = new PostCompanySalaryCalcInfo();
            info.setCompanyId(companyId);
            info.setUsername(username).setCreateTime(System.currentTimeMillis()).setDelFlag(0).setSalaryMonthCount(0).setSalaryMonthDate(System.currentTimeMillis());
            try {
                UserDaoSql.getInstance().saveObj(PojoTables.POST_COMPANY_CALC_SALARY, info);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return info;
    }

    // 更新缓存
    public void reload(String username, Long companyId) {
        dataMap.remove(getKey(username, companyId));
    }

    private static String getKey(String username, Long companyId) {
        return username + "-" + companyId;
    }

}
